package website.haicheng.picturemanage.service.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import website.haicheng.picturemanage.commo.exceptions.ConstraintNotMatchException;
import website.haicheng.picturemanage.service.WeChatService;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

import static website.haicheng.picturemanage.commo.util.Assert.stat;

/**
 * @author haicheng.long@androidmov.com
 * @ClassName WeChatServiceImpl
 * @Description TODO
 * @date 2020/11/6 下午 3:19
 */
@Slf4j
@Service
public class WeChatServiceImpl implements WeChatService {

    @Value(value = "${weChat.appId}")
    private String appId;

    @Value(value = "${weChat.appKey}")
    private String appSecret;

    @Value(value = "${weChat.accessTokenUrl}")
    private String accessTokenUrl;


    /**
     * access_token
     */
    private static final String ACCESS_TOKEN = "access_token";

    @Resource
    private StringRedisTemplate stringRedisTemplate;


    /**
     * 获取access_token
     *
     * @return
     */
    @Override
    public String getAccessToken() {
        String token = stringRedisTemplate.opsForValue().get(ACCESS_TOKEN);
        if (StringUtils.hasLength(token)) {
            return token;
        }
        long start = System.currentTimeMillis();
        String url = accessTokenUrl + "?grant_type=client_credential" + "&appid=" + appId + "&secret=" + appSecret;
        HttpResponse response = HttpRequest.get(url).execute();
        stat(!response.isOk(), "获取AccessToken异常！");
        log.info("通过URL获取accessToken;耗时：{}ms", System.currentTimeMillis() - start);
        JSONObject jsonObject = JSONUtil.parseObj(response.body());
        if (jsonObject.containsKey("errcode")) {
            log.warn("获取accessToken异常，url:{};response:{}", url, jsonObject);
            throw new ConstraintNotMatchException("获取AccessToken异常");
        }
        String accessToken = jsonObject.getStr("access_token");
        Integer expires = jsonObject.getInt("expires_in");
        stringRedisTemplate.opsForValue().set(ACCESS_TOKEN, accessToken, expires - 2000, TimeUnit.SECONDS);
        return accessToken;
    }

    @Override
    public boolean deleteMenu(String token) {
        String url = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=" + token;
        HttpResponse response = HttpRequest.get(url).execute();
        stat(!response.isOk(), "删除菜单异常！");
        JSONObject jsonObject = JSONUtil.parseObj(response.body());
        if (!jsonObject.containsKey("errcode") || 0 != jsonObject.getInt("errcode")) {
            log.warn("删除菜单失败；url:{};response:{}", url, jsonObject.toString());
            return false;
        }
        return true;
    }
}
